import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
  PageContainer,
  ProDescriptions,
  ProTable,

} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Drawer, message, Popconfirm} from 'antd';
import React, {useRef, useState} from 'react';
import {SortOrder} from "antd/es/table/interface";
import {
  addDataSourceUsingPost, datasourceOperationUsingPost, deleteDatasourceUsingPost,
  pageDatasourceUsingPost,
  testDatasourceConnectUsingPost
} from "@/services/easyapi/eDatasource";
import AddModal from "@/pages/DataSourceTableList/components/DatasourceAddModal";
import UpdateModal from "@/pages/DataSourceTableList/components/UpdateModal";
import {history} from "@umijs/max";


const DataSourceTableList: React.FC = () => {
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.DataSourcePageVo>();
  const [addModalVisible, setAddModalVisible] = useState<boolean>(false)
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false)

  const testConnect = async (datasourceParam: API.AddDatasourceParam) => {
    await testDatasourceConnectUsingPost({
      ...datasourceParam
    }).then(res => {
      console.log(res)
      if (res.code && res.code === 200) {
        message.success('连接成功')
      }
      if (res.code && res.code !== 200) {
        message.error('连接失败');
      }
    }).catch(() => {
      message.error('连接失败')
    })
  }

  const datasourceOperation = async (id: number, action: string) => {
    const res = await datasourceOperationUsingPost({
      action: action,
      id: id
    });
    if (res.code === 200) {
      message.success("操作成功")
    } else {
      message.error(res.msg)
    }
    actionRef.current?.reload();
  }

  const deleteDatasource = async (id: number) => {
    const res = await deleteDatasourceUsingPost({
      id: id
    });
    if (res.code === 200) {
      message.success('删除成功')
    } else {
      message.error(res.msg)
    }
    actionRef.current?.reload();
  }

  // @ts-ignore
  const columns: ProColumns<API.DataSourcePageVo>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      hideInForm: true,
      hideInSearch: true
    },
    {
      title: '数据源名称',
      dataIndex: 'dataName',
      hideInForm: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入数据源名称'
          },
          {
            max: 20,
            message: '数据源名称长度不能超过20'
          },
          {
            min: 2,
            message: '数据源名称长度不能少于2'
          }
        ]
      }
    },
    {
      title: '数据源描述',
      dataIndex: 'dataDesc',
      hidden: true,
      hideInForm: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入数据源描述'
          },
          {
            max: 20,
            message: '数据源描述长度不能超过20'
          },
          {
            min: 2,
            message: '数据源描述长度不能少于2'
          }]
      }
    },
    {
      title: '用户名',
      dataIndex: 'datasourceUsername',
      hideInSearch: true,
      hideInForm: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入用户名'
          },
          {
            max: 255,
            message: '用户名长度不能超过255'
          },
          {
            min: 2,
            message: '用户名长度不能少于2'
          }]
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: "正常",
          color: 'green'
        },
        1: {
          text: '禁用',
          color: 'red'
        }
      }
    },
    {
      title: '用户密码',
      dataIndex: 'datasourcePassword',
      hideInForm: false,
      hideInSearch: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入用户密码'
          },
          {
            max: 255,
            message: '用户密码长度不能超过255'
          },
          {
            min: 2,
            message: '用户密码长度不能少于2'
          }
        ]
      }
    },
    {
      title: '数据源类型',
      dataIndex: 'type',
      valueEnum: {
        1: {
          text: 'MYSQL',
          status: 'Processing',
        },
        2: {
          text: 'ORACLE',
          status: 'Processing',
        },
        3: {
          text: 'SQLSERVER',
          status: 'Processing',
        }
      }
    },
    {
      title: 'url',
      dataIndex: 'dataJson',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入url'
          },
          {
            max: 255,
            message: 'url长度不能超过255'
          },
          {
            min: 2,
            message: 'url长度不能少于2'
          }]
      }
    },
    {
      title: '数据源状态',
      dataIndex: 'active',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '未启用',
          status: 'Default',
        },
        2: {
          text: '初始化',
          status: 'Default',
        },
        1: {
          text: '使用中',
          status: 'Processing',
        },
      },
    },
    {
      title: '连接状态',
      dataIndex: 'linkState',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '连接丢失',
          status: 'Default'
        },
        1: {
          text: '连接可用',
          status: 'Processing'
        },
        2: {
          text: '连接中',
          status: 'Processing'
        }
      }
    },
    {
      title:'创建时间',
      dataIndex:'createAt',
      valueType:'dateTime',
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        record.status === 0 ?
          <a style={{color: 'rosybrown'}}
             key={"testLink"}
             onClick={() => {
               testConnect(record)
             }}>链接测试</a> : null,
        record.status === 0 ?
          <a style={{color: 'green'}}
             onClick={() => {
            setUpdateModalVisible(true)
            setCurrentRow(record)
          }}>更新</a> : null,
        record.status === 0 ?
          <Popconfirm
            title={"确认要禁用该数据源吗?该操作会导致无法对数据源进行其他操作"}
            onConfirm={() => {
              if (record !== null && record.id !== undefined && record.id !== null) {
                datasourceOperation(record.id, "bind_datasource")
              }
            }}>
            <a style={{color: 'purple'}}>禁用</a>
          </Popconfirm>
          :
          <Popconfirm
            title={"确认恢复该数据源吗?"}
            onConfirm={() => {
              if (record !== null && record.id !== undefined && record.id !== null) {
                datasourceOperation(record.id, "life_datasource")
              }
            }}>
            <a style={{color: 'blue'}}>恢复</a>
          </Popconfirm>,
        record.status === 0 ?
          <Popconfirm
            title={"确认要删除该数据源吗"}
            onConfirm={() => {
              if (record !== null && record.id !== undefined && record.id !== null) {
                deleteDatasource(record.id)
              }
            }}
          >
            <a style={{color: 'red'}}>删除</a>
          </Popconfirm> : null,
        record.status === 0 ?
          // eslint-disable-next-line @typescript-eslint/no-use-before-define
          <a key={"detail"} style={{color: 'green'}} title={"详情"}>{renderLink(record)}</a> : null
      ]
    },
  ];
  const renderLink = (record: any) => {
    if (record.linkState === 1) {
      return (
        <a
          key="config0"
          onClick={() => {
            localStorage.setItem("dataSourceId", record.id)
            history.push('/datasource/detail')
          }}
        >
          详情
        </a>
      );
    }
    return null; // 如果 linkStatus 不是 1，则不渲染任何内容
  };
  // @ts-ignore
  return (
    <PageContainer>
      <ProTable<API.DataSourcePageVo, API.DataSourcePageParam>
        headerTitle={'数据源列表'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [<Button key="add" type="primary" onClick={() => {
          setAddModalVisible(true)
        }}>新增数据源</Button>]
        }
        request={async (params
          , sort: Record<string, SortOrder>, filter: Record<string, React.ReactText[] | null>) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          const res = await pageDatasourceUsingPost({
            ...params
          } as API.DataSourcePageParam);
          if (res.code === 200) {
            return {
              // @ts-ignore
              data: res?.data.records,
              success: true,
              // @ts-ignore
              total: res?.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
      />
      {/*@ts-ignore*/}
      <AddModal columns={columns} onCancel={() => {
        setAddModalVisible(false)
      }}
                onSubmit={async (values) => {
                  await addDataSourceUsingPost({
                    ...values
                  }).then(res => {
                    if (res.code === 200) {
                      message.success('添加成功')
                      setAddModalVisible(false)
                      actionRef.current?.reload()
                    } else {
                      message.error(res.msg)
                    }
                  }).catch(() => {
                    message.error('添加失败')
                  })
                }} visible={addModalVisible}/>
      <UpdateModal values={currentRow || {}} columns={columns} onCancel={() => {
        setUpdateModalVisible(false)
        setCurrentRow(undefined)
      }} onSubmit={async (values) => {
       const res = await addDataSourceUsingPost({
          id: currentRow?.id,
          dataDesc: values.dataDesc,
          dataName: values.dataName,
          dataJson: values.dataJson,
          datasourceUsername: values.datasourceUsername,
          datasourcePassword: values.datasourcePassword,
          type: values.type
        })
        if(res.code===200){
          message.success('更新成功')
        } else{
          message.error(res.msg)
        }
      }} visible={updateModalVisible}/>
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.dataName && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.dataName}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};
export default DataSourceTableList;
